const db = require("../config/db");
const bcrypt = require("bcryptjs");

class User {
  static async findByUsername(username) {
    const [rows] = await db.query("SELECT * FROM users WHERE username = ?", [
      username,
    ]);
    return rows[0];
  }

  static async findById(id) {
    const [rows] = await db.query("SELECT * FROM users WHERE id = ?", [id]);
    return rows[0];
  }

  static async findAll() {
    const [rows] = await db.query("SELECT id, username, role, status FROM users ORDER BY id ASC");
    return rows;
  }

  static async findByPage(offset, limit) {
    const [rows] = await db.query(
      "SELECT id, username, role, status FROM users ORDER BY id ASC LIMIT ?, ?",
      [offset, limit]
    );
    return rows;
  }

  static async getTotalCount() {
    const [rows] = await db.query("SELECT COUNT(*) as total FROM users");
    return rows[0].total;
  }

  static async create(userData) {
    const { username, password, role = "user", status = 1 } = userData;
    const hashedPassword = await bcrypt.hash(password, 10);
    const [result] = await db.query(
      "INSERT INTO users (username, password, role, status) VALUES (?, ?, ?, ?)",
      [username, hashedPassword, role, status]
    );
    return result.insertId;
  }

  static async verifyPassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
  }

  static async update(id, userData) {
    const { username, password, role, status } = userData;
    let updateFields = [];
    let params = [];

    if (username) {
      updateFields.push("username = ?");
      params.push(username);
    }
    if (password) {
      const hashedPassword = await bcrypt.hash(password, 10);
      updateFields.push("password = ?");
      params.push(hashedPassword);
    }
    if (role) {
      updateFields.push("role = ?");
      params.push(role);
    }
    if (status !== undefined) {
      updateFields.push("status = ?");
      params.push(status);
    }

    if (updateFields.length === 0) {
      return false;
    }

    params.push(id);
    const [result] = await db.query(
      `UPDATE users SET ${updateFields.join(", ")} WHERE id = ?`,
      params
    );
    return result.affectedRows > 0;
  }

  static async delete(id) {
    const [result] = await db.query("DELETE FROM users WHERE id = ?", [id]);
    return result.affectedRows > 0;
  }
}

module.exports = User;
